package com.li.service.impl;

import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import com.li.service.GuavaBloomFilterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

/**
 * INFO  com.li.service.impl.GuavaBloomFilterServiceImpl- 误判个数:3033
 * fpp 0.03
 * 不存在的数据10w
 * 3033/10w 等于0.03033 ≈ fpp
 */
@Service
@Slf4j
public class GuavaBloomFilterServiceImpl implements GuavaBloomFilterService {
    public static final int _1W =10000;
    public static final int _Amount =100;
    //Guava过滤器初始容量
    public static final int size = _1W * _Amount;
    //误判率,数字越小,误判个数越少(todo 思考,为什么是0.03 ,是否可以是无限小,没有误判岂不是更好?)
    public static double fpp =0.01;
    //创建Guava版布隆过滤器
    private static BloomFilter<Integer> filter = BloomFilter.create(Funnels.integerFunnel(),size,fpp);

    public void guavaBloomFilter(){
        //先让BloomFilter加入100w白名单数据
        for(int i=0;i<size;i++){
            filter.put(i);
        }
        //故意取10w个不在合法范围内的数据,来进行误判率的演示
        //ArrayList<>() 初始容量10w ,最多10w条不合格数据
        ArrayList<Integer> list = new ArrayList<>(10*_1W);
        //验证,将误判的放到list中
        for(int i=size+1;i<size+(10*_1W);i++){
            if (filter.mightContain(i)){
                log.info("误判了:{}",i);
                list.add(i);
            }
        }
        log.info("误判个数:{}",list.size());
    }

}
